package com.xiejr.context;


import com.xiejr.model.exception.BusinessException;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @program: fasttm
 * @description: 项目上下文
 * @author: xjr
 * @create: 2020-07-21 10:52
 **/

public class ApplicationContextHolder {

    public static final String T = "token";
    public static final String TS = "timestamp";
    public static final String SIGN = "sign";
    public static final String IP="ip";


    private static final ThreadLocal<Map<String, String>> HOLDER = ThreadLocal.withInitial(
            () -> new HashMap<>(20)
    );

    public static String get(String key) {
        return HOLDER.get().getOrDefault(key, null);
    }

    public static String getOrThrow(String key) throws BusinessException {
        return Optional.ofNullable(get(key)).orElseThrow(() -> new BusinessException("找不到指定的上下文值,key=" + key));
    }

    public static void set(String key, String value) {
        HOLDER.get().put(key, value);
    }

    public static void clear() {
        HOLDER.remove();
    }

    public static String getCurrentToken() throws BusinessException{
        return Optional.ofNullable(get(T)).orElseThrow(()->new BusinessException("非法请求无令牌"));
    }
}
